//
//  SearchModelView.swift
//  ezyform
//
//  Created by Moennig Q on 8/9/2022.
//  Copyright © 2022 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import SwiftyJSON
import HandyJSON
enum SearchModelType: Int{
    case panel = 0
    case inverter
    case battery
    case tank
}
class SearchModelView: UIView {
    private var type: SearchModelType = .panel
    private var installationDate: String = ""
    var selectClosure: ((SearchDictionaryModel)->Void)?
    let tableView = TableView()
    var list = [SearchDictionaryModel]()
    let titleLabel = ContentLabel(R.font.interSemiBold(size: 17))
    let searchTextfield = DIYTextField()
    //用于延时500ms搜索地址
    var delaySearchTimer: Timer?
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    init(_ type: SearchModelType,title: String, defaultSearchValue: String, installDate: String ) {
        super.init(frame: CGRect.zero)
        self.type = type
        self.searchTextfield.text = defaultSearchValue
        self.titleLabel.text = title
        self.installationDate = installDate
        setUpView()
    }
    private func setUpView() {
        self.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        let backView = UIView()
        backView.drawCorner(byRoundingCorners: [.topLeft,.topRight])
        self.addSubview(backView)
        backView.snp.makeConstraints { make in
            make.top.equalTo(self.safeAreaLayoutGuide.snp.top).offset(40)
            make.left.right.bottom.equalToSuperview()
        }
        //modelSelectLabel
        backView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(30)
            make.centerX.equalToSuperview()
            make.height.width.greaterThanOrEqualTo(0)
        }
        //Done btn
        let closeBtn = UIButton()
        closeBtn.setImage(R.image.me_presentvc_close(), for: UIControl.State.normal)
        backView.addSubview(closeBtn)
        closeBtn.snp.makeConstraints { make in
            make.right.equalTo(-8)
            make.width.height.equalTo(40)
            make.centerY.equalTo(titleLabel)
        }
        let searchBackView = UIView()
        searchBackView.backgroundColor = UIColor(hexStr: "#F5F5F5")
        backView.addSubview(searchBackView)
        searchBackView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(15)
            make.height.greaterThanOrEqualTo(0)
            make.left.right.equalToSuperview()
        }
        
        searchTextfield.showLeftImageView("edit_address_search_icon")
        searchTextfield.enabledAutoAdjustFontSize()
        searchBackView.addSubview(searchTextfield)
        searchTextfield.snp.makeConstraints { make in
            make.top.equalTo(12)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(40)
            make.bottom.equalTo(-12)
        }
        //
        backView.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(searchBackView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        //
        searchTextfield.delegate = self
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(SearchModellCell.self, forCellReuseIdentifier: SearchModellCell.reuseCellIdentifier)
        //
        closeBtn.addTarget(self, action: #selector(closeBtnClick), for: UIControl.Event.touchUpInside)
        
        searchTextfield.addTarget(self, action: #selector(textFieldEditChanged(_:)), for: UIControl.Event.editingChanged)
        searchTextfield.delegate = self
        tableView.loadFaildView.retryBtn.addTarget(self, action: #selector(retryBtnClick), for: UIControl.Event.touchUpInside)
        self.initData()
        self.searchModelList()
    }
    private func initData(){
        var content: String = ""
        if type == .panel {
            content = "Search by Brand and Power e.g. \"Risen 415W\""
        }else if type == .inverter{
            content = "Search by Manufacturer and Model/Power e.g. \"GoodWe 5kW\""
        }else if type == .battery{
            content = "Search by Manufacturer and Model/Capacity e.g. \"Alpha 5kWh\""
        }else if type == .tank{
            content = "Search by Manufacturer and Model"
        }
        self.searchTextfield.placeholder = content
    }
    @objc private func retryBtnClick(){
        self.searchModelList()
    }
    @objc func textFieldEditChanged(_ textField: UITextField){
        self.delaySearchTimer?.invalidate()  // Cancel any previous timer
        self.delaySearchTimer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(searchModelList), userInfo: nil, repeats: false)
    }
    @objc func closeBtnClick(){
        self.removeFromSuperview()
    }
    @objc func searchModelList(){
        let queryStr = self.searchTextfield.text ?? ""
        let vm = DictionaryService()
        vm.setBlockAfterNetwork { [weak self] (result, _) in
            guard let strongSelf = self else {return}
            ModelViewUtil.shared.hideLoadingView()
            let json = JSON(result!)
            if let list = JSONDeserializer<SearchDictionaryModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<SearchDictionaryModel>{
                strongSelf.list = list
                strongSelf.tableView.reloadData()
            }
            //没有数据显示not data view，有数据隐藏not data view
            strongSelf.tableView.showResultView(nodataFlag: strongSelf.list.count == 0 ? true: false)
        } errorBlock: { [weak self](code, error) in
            guard let strongSelf = self else {return}
            ModelViewUtil.shared.hideLoadingView()
            strongSelf.list.removeAll()
            strongSelf.tableView.reloadData()
            strongSelf.tableView.showRetryView()
            Tool().showAlertViewWithOneBtn(message: error)
        }
        if type == .tank{
            if queryStr.count >= 3 {
                ModelViewUtil.shared.showLoadingView(parentView: self)
                vm.getTankModels(queryStr,installationDate: self.installationDate)
            }
        }else {
            ModelViewUtil.shared.showLoadingView(parentView: self)
            if type == .inverter {
                vm.getInverterModels(queryStr,installationDate: self.installationDate)
            }else if type == .panel{
                vm.getPanelModels(queryStr,installationDate: self.installationDate)
            }else if type == .battery{
                vm.getBatteryModels(queryStr,installationDate: self.installationDate)
            }
        }
    }
}
extension SearchModelView: UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.list.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: SearchModellCell.reuseCellIdentifier) as? SearchModellCell
        if cell == nil {
            cell = SearchModellCell(style: .default, reuseIdentifier: SearchModellCell.reuseCellIdentifier)
        }
        cell!.setData(self.list[indexPath.row],type: self.type)
        return cell!
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.selectClosure?(self.list[indexPath.row])
        self.removeFromSuperview()
    }
}
